<template>
  <div
    v-if="viewMode === 'edit'"
    style="display: flex; justify-content: space-around; gap: 24px"
  >
    <a-input :disabled="true" v-model:value="selectText">
      <template #addonAfter v-if="!disabled">
        <EnvironmentFilled style="color: #0960bd" @click="open" /> </template
    ></a-input>
  </div>
  <div v-else>{{ selectText }}</div>
  <BasicModal
    v-bind="$attrs"
    width="50%"
    title="标记区块"
    default-fullscreen
    @register="registerModal"
    @ok="submit"
  >
    <RadioGroup
      v-model:value="addressType"
      @change="(e) => handleSwitchType(e.target.value)"
    >
      <RadioButton value="0">地址</RadioButton>
      <RadioButton value="1">区域</RadioButton>
    </RadioGroup>
    <a-input-search
      v-model:value="searchPoi"
      placeholder="查找地点"
      style="width: 300px"
      allowClear
      @search="onSearch"
    />
    <div ref="container" style="height: 100%"></div>
  </BasicModal>
</template>
<script setup lang="ts">
import { ref, watch, unref, toRaw } from 'vue';
import { RadioGroup, RadioButton } from 'ant-design-vue';
import { EnvironmentFilled } from '@ant-design/icons-vue';
import { BasicModal, useModal } from '@/components/Modal';
import AMapLoader from '@amap/amap-jsapi-loader';
import { useRuleFormItem } from '@/hooks/component/useFormItem';
import setting from '@/settings/projectSetting';
const props = defineProps({
  value: {
    type: String,
  },
  viewMode: {
    type: String,
  },
  adsType: {
    type: String,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});
// 选择类型
const addressType = ref(props.adsType);
const marker = ref();
const address = ref('');

const emit = defineEmits(['submit', 'update:value', 'change']);
const mapInstance = ref();
const searchPoi = ref('');
const container = ref();
let polyEditor;
const selectText = ref('未选择');

const emitData = ref<any>([]);

let polyLineArr = [];
let _AMap: Recordable = {};
let onSearch;
const [registerModal, { openModal, closeModal }] = useModal();
watch(
  () => props.value,
  (v) => {
    selectText.value = v ? '已选择' : '未选择';
  },
  {
    immediate: true,
  },
);
// 触发父组件赋值
const setValue = () => {
  const value =
    addressType.value === '1' ? JSON.stringify(polyLineArr) : address.value;
  emitData.value = value;
  emit('update:value', value);
  emit('change', value, addressType.value);
};

// 逆地址解析
const getAddress = (lnglat, callback) => {
  const geocoder = new _AMap.Geocoder();
  geocoder.getAddress(lnglat, function (status, result) {
    if (status === 'complete' && result.regeocode) {
      selectText.value = result.regeocode.formattedAddress;
      callback(selectText.value);
    } else {
      selectText.value = '';
      callback('根据经纬度查询地址失败');
    }
  });
};
const addMarker = (e) => {
  const { lat, lng } = e.lnglat;
  const position = [lng, lat];
  if (unref(marker)) {
    marker.value.remove();
  }
  address.value = position.join(',');
  // pos.value = position;
  getAddress(position, (labelContent) => {
    marker.value = new _AMap.Marker({
      position,
      label: {
        content: labelContent,
      },
      icon: new _AMap.Icon({
        image:
          '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
        size: new _AMap.Size(20, 28),
        imageSize: new _AMap.Size(20, 28),
      }),
      offset: new _AMap.Pixel(0, 0),
      anchor: 'bottom-center',
    });
    marker.value.setMap(mapInstance.value);
    setValue();
  });
};
const initPoint = () => {
  mapInstance.value.off('click', addMarker);
  mapInstance.value.on('click', addMarker);
};
const isPolyContextMenu = ref<boolean>(false);
// 触发父组件赋值
const initPolyLines = () => {
  //
  // 初始化连线
  if (props.value) {
    const temp: Recordable = [];
    if (typeof props.value == 'string') {
      polyLineArr = JSON.parse(props.value);
    } else {
      polyLineArr = props.value;
    }

    polyLineArr.forEach((path) => {
      const currentPl = new _AMap.Polygon({
        path,
        borderWeight: 1,
      });
      bindPolyLineEvent(currentPl);
      mapInstance.value.add(currentPl);
      temp.push(currentPl);
    });
    polyEditor.addAdsorbPolygons(temp);
    mapInstance.value.setFitView();
  }
};

const bindPolyLineEvent = (polyLine) => {
  const contextMenu = new _AMap.ContextMenu();
  contextMenu.addItem(
    '删除',
    function (e) {
      mapInstance.value.remove(polyLine);
      contextMenu.close();
      polyEditor.setTarget();
    },
    0,
  );

  // 绑定双击事件
  polyLine.on('dblclick', () => {
    polyEditor.setTarget(polyLine);
    polyEditor.open();
  });
  // 绑定右键事件
  polyLine.on('rightclick', function (e) {
    isPolyContextMenu.value = true;
    contextMenu.open(mapInstance.value, e.lnglat);
    // contextMenu.value.close();
  });
};
const createMapContextMenu = () => {
  const menu = new _AMap.ContextMenu();
  menu.addItem(
    '创建多边形区块',
    function (e) {
      console.log(e, '创建多边形');
      createPolygon();
      menu.close();
    },
    0,
  );
  mapInstance.value.on('rightclick', function (e) {
    if (isPolyContextMenu.value) {
      isPolyContextMenu.value = false;
      return;
    }
    menu.open(mapInstance.value, e.lnglat);
  });
};
const createPolyEditor = () => {
  if (polyEditor) return;
  polyEditor = new _AMap.PolygonEditor(mapInstance.value);
  const pE = polyEditor;
  // 设置吸附

  pE.on('add', function (data) {
    var polygon = data.target;
    bindPolyLineEvent(polygon);
  });
};
const handleSwitchType = (v) => {
  mapInstance.value.clearMap();
  if (v === '0') {
    initPoint();
    clearPolyEditor();
  } else {
    mapInstance.value.off('click', addMarker);
    createMapContextMenu();
    createPolyEditor();
  }
};
const initMap = async () => {
  const AMap = await AMapLoader.load({
    key: setting.mapKey,
    version: '2.0',
    plugins: [
      'AMap.Geocoder',
      'AMap.PolygonEditor',
      'AMap.ContextMenu',
      'AMap.PlaceSearch',
    ],
  });
  _AMap = AMap;
  mapInstance.value = new _AMap.Map(container.value, {});
  handleSwitchType(addressType.value);
  //构造地点查询类
  const placeSearch = new _AMap.PlaceSearch({
    map: mapInstance.value,
  });
  onSearch = (keyword) => {
    placeSearch.search(keyword);
  };
};

const clearPolyEditor = () => {
  if (!polyEditor) return;
  polyEditor.setTarget();
  polyEditor.close();
};
const createPolygon = () => {
  clearPolyEditor();
  polyEditor.open();
};

const open = () => {
  polyLineArr = [];
  openModal(true, {});
  addressType.value = props.adsType;
  if (!mapInstance.value) {
    setTimeout(() => {
      initMap();
    });
  }
  if (addressType.value === '1') {
    const inv = setInterval(() => {
      if (mapInstance.value) {
        mapInstance.value.clearMap();
        createPolyEditor();
        clearInterval(inv);
        initPolyLines();
      }
    });
  } else if (addressType.value === '0') {
    const inv = setInterval(() => {
      if (mapInstance.value) {
        if (props.value) {
          const poi = props.value.split(',');
          if (poi.length !== 2) return;
          addMarker({ lnglat: { lng: poi[0], lat: poi[1] } });
          clearInterval(inv);
        }
      }
    });
  }
};

// 确定提交
const submit = () => {
  polyLineArr = [];
  if (addressType.value === '1') {
    mapInstance.value.getAllOverlays('polygon').forEach((p) => {
      const { path } = p.getOptions();
      polyLineArr.push(toRaw(path) as number[]);
    });
  }
  if (!address.value && polyLineArr.length === 0) {
    selectText.value = '未选择';
  } else {
    selectText.value = '已选择';
  }
  setValue();
  closeModal();
};
</script>
<style>
#container {
  height: 100%;
}
</style>
